package com.example.znyt.manage.upload;

import cn.hutool.core.io.FileUtil;
import com.example.znyt.exception.ErrorCode;
import com.example.znyt.utils.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * @Description 文件图片上传
 * @Date 2025/6/21 09:56
 * @Created by 12336
 */

@Service
public class FilePictureUpload extends PictureUploadTemplate{

    @Override
    protected void validPicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "上传文件不能为空");
        //1.校验文件大小
        long fileSize  = multipartFile.getSize();
        final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
        ThrowUtils.throwIf(fileSize > TWO_MB, ErrorCode.PARAMS_ERROR,"文件大小不能超过2M");
        //2.校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");

    }

    /**
     * 获取输入源的原始文件名
     * @param inputSource
     * @return
     */
    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    /**
     * 处理输入源生成本地临时文件
     * @param inputSource
     * @param file
     * @throws Exception
     */
    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
